<!DOCTYPE HTML>
<html lang>
<head><meta name="generator" content="Hexo 3.9.0">
    <!--Setting-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta name="apple-mobile-web-app-capable" content="腾宇的个人博客">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    <meta name="browsermode" content="application">
    <meta name="screen-orientation" content="portrait">
    <meta name="theme-version" content="1.2.3">
    <meta name="root" content="/blog/">
    <link rel="dns-prefetch" href="https://gitee.com/bingtengaoyu/blog">
    <!--SEO-->

    <meta name="keywords" content>


    <meta name="description" content="@(作者)[腾宇]

1、简而言之 dva 是基于现有应用架构 (redux + react-router + redux-saga 等) 的一层轻量封装2、在 web 应用中，数据的改变通常发...">



<meta name="robots" content="all">
<meta name="google" content="all">
<meta name="googlebot" content="all">
<meta name="verify" content="all">

    <!--Title-->


<title>React - dva 数据流 | 腾宇的个人博客</title>


    <link rel="alternate" href="/atom.xml" title="腾宇的个人博客" type="application/atom+xml">


    <link rel="icon" href="/favicon.ico">

    



<link rel="stylesheet" href="/blog/css/bootstrap.min.css?rev=3.3.7">
<link rel="stylesheet" href="/blog/css/font-awesome.min.css?rev=4.5.0">
<link rel="stylesheet" href="/blog/css/style.css?rev=@@hash">




    
	<div class="hide">
		<script type="text/javascript">
			var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan class='cnzz_stat_icon_1263868967 hide' %3E%3Cscript%20src%3D%22https%3A%2F%2Fs95.cnzz.com%2Fz_stat.php%3Fweb_id%3D1272564536%22%3E%3C%2Fscript%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1263868967%26show%3Dpic1' type='text/javascript'%3E%3C/script%3E"));
		</script>
	</div>






    

</head>

</html>
<!--[if lte IE 8]>
<style>
    html{ font-size: 1em }
</style>
<![endif]-->
<!--[if lte IE 9]>
<div style="ie">你使用的浏览器版本过低，为了你更好的阅读体验，请更新浏览器的版本或者使用其他现代浏览器，比如Chrome、Firefox、Safari等。</div>
<![endif]-->

<body>
    <header class="main-header"  style="background-image:url(http://snippet.shenliyang.com/img/banner.jpg)"  >
    <div class="main-header-box">
        <a class="header-avatar" href="/" title='耿兵兵'>
            <img src="/blog/img/avatar.jpg" alt="logo头像" class="img-responsive center-block">
        </a>
        <div class="branding">
        	<!--<h2 class="text-hide">Snippet主题,从未如此简单有趣</h2>-->
            
                 <img src="/blog/img/branding.png" alt="Snippet 博客主题" class="img-responsive center-block">
            
    	</div>
    </div>
</header>
    <nav class="main-navigation">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="navbar-header"><span class="nav-toggle-button collapsed pull-right" data-toggle="collapse" data-target="#main-menu" id="mnav">
                    <span class="sr-only"></span>
                        <i class="fa fa-bars"></i>
                    </span>
                    <a class="navbar-brand" href="https://gitee.com/bingtengaoyu/blog">腾宇的个人博客</a>
                </div>
                <div class="collapse navbar-collapse" id="main-menu">
                    <ul class="menu">
                        
                            <li role="presentation" class="text-center">
                                <a href="/blog"><i class="fa "></i>Home</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="https://bingtengaoyu.gitee.io/vuetools/#/"><i class="fa "></i>vue插件</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="https://bingtengaoyu.gitee.io/reactantd/#/"><i class="fa "></i>reactAnt模板</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="https://bingtengaoyu.gitee.io/home/"><i class="fa "></i>简介</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="http://gank.io/"><i class="fa "></i>工具</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="/blog/archives/"><i class="fa "></i>时间轴</a>
                            </li>
                        
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
    <section class="content-wrap">
        <div class="container">
            <div class="row">
                <main class="col-md-8 main-content m-post">
                    <p id="process"></p>
<article class="post">
    <div class="post-head">
        <h1 id="React - dva 数据流">
            
	            React - dva 数据流
            
        </h1>
        <div class="post-meta">
    
        <span class="categories-meta fa-wrap">
            <i class="fa fa-folder-open-o"></i>
            
        </span>
    

    
        <span class="fa-wrap">
            <i class="fa fa-tags"></i>
            <span class="tags-meta">
                
            </span>
        </span>
    

    
        
        <span class="fa-wrap">
            <i class="fa fa-clock-o"></i>
            <span class="date-meta">2019/07/29</span>
        </span>
        
    
</div>
            
            
    </div>
    
    <div class="post-body post-content">
        <p>@(作者)[腾宇]</p>
<blockquote>
<p>1、简而言之 dva 是基于现有应用架构 (redux + react-router + redux-saga 等) 的一层轻量封装<br>2、在 web 应用中，数据的改变通常发生在用户交互行为或者浏览器行为（如路由跳转等），当此类行为改变数据的时候可以通过 dispatch 发起一个 action，如果是同步行为会直接通过 Reducers 改变 State ，如果是异步行为会先触发 Effects 然后流向 Reducers 最终改变 State，所以在 dva 中，数据流向非常清晰简明，并且思路基本跟开源社区保持一致。</p>
</blockquote>
<h3 id="启动一个-dva-应用"><a href="#启动一个-dva-应用" class="headerlink" title="启动一个 dva 应用"></a>启动一个 dva 应用</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Install dva-cli</span></span><br><span class="line">$ npm install dva-cli -g</span><br><span class="line"></span><br><span class="line"><span class="comment">// Create app and start</span></span><br><span class="line">$ dva <span class="keyword">new</span> myapp</span><br><span class="line">$ cd myapp</span><br><span class="line">$ npm install</span><br><span class="line">$ npm start</span><br></pre></td></tr></table></figure>

<h4 id="1、dva-项目-src-目录结构"><a href="#1、dva-项目-src-目录结构" class="headerlink" title="1、dva 项目 src 目录结构"></a>1、dva 项目 src 目录结构</h4><ul>
<li><strong>assets: 我们可以把项目 assets 资源丢在这边</strong></li>
<li><strong>components: 纯组件，在 dva 应用中 components 目录中应该是一些 logicless 的 - - component, logic 部分均由对应的 route-component 来承载。在安装完 dva-cli 工具后，我们可以通过 dva g component componentName 的方式来创建一个 component。</strong></li>
<li><strong>index.css: 首页样式</strong></li>
<li><strong>index.html: 首页</strong></li>
<li><strong>index.js: dva 应用启动 五部曲，这点稍后再展开</strong></li>
<li><strong>models: 该目录结构用以存放 model，在通常情况下，一个 model 对应着一个 - route-component，而 route-component 则对应着多个 component，当然这取决于你如何拆分，个人偏向于尽可能细粒度的拆分。在安装完 dva-cli 工具后，我们可以通过 dva g model modelName 的方式来创建一个 model。该 model 会在 index.js 中自动注册。</strong></li>
<li><strong>router.js: 页面相关的路由配置，相应的 route-component 的引入</strong></li>
<li><strong>routes: route-component 存在的地方，在安装完 dva-cli 工具后，我们可以通过 dva g route route-name 的方式去创建一个 route-component，该路由配置会被自动更新到 route.js 中。route-component 是一个重逻辑区，一般业务逻辑全部都在此处理，通过 connect 方法，实现 model 与 component 的联动。</strong></li>
<li><strong>services: 全局服务，如发送异步请求</strong></li>
<li><strong>tests: 测试相关</strong></li>
<li><strong>utils: 全局类公共函数</strong></li>
</ul>
<h4 id="2、官网解释"><a href="#2、官网解释" class="headerlink" title="2、官网解释"></a>2、官网解释</h4><p><strong>2.1、State</strong><br>State 表示 Model 的状态数据，通常表现为一个 javascript 对象（immutable data）。</p>
<p><strong>2.2、Action</strong><br>Action 是一个普通 javascript 对象，它是改变 State 的唯一途径。无论是从 UI 事件、网络回调，还是 WebSocket 等数据源所获得的数据，最终都会通过 dispatch 函数调用一个 action，从而改变对应的数据。<br>需要注意的是 dispatch 是在组件 connect Models 以后，通过 props 传入的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">dispatch(&#123;</span><br><span class="line">  type: <span class="string">'user/add'</span>, <span class="comment">// 如果在 model 外调用，需要添加 namespace</span></span><br><span class="line">  payload: &#123;&#125;, <span class="comment">// 需要传递的信息</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>以上调用函数内的对象就是一个 action。</strong></p>
<p><strong>2.3、dispatch 函数</strong><br>用于触发 action 的函数，action 是改变 State 的唯一途径，但是它只描述了一个行为，而 dipatch 可以看作是触发这个行为的方式，而 Reducer 则是描述如何改变数据的。<br><strong>2.4、dva - Reducer</strong><br>在 dva 中，reducers 聚合积累的结果是当前 model 的 state 对象。通过 actions 中传入的值，与当前 reducers 中的值进行运算获得新的值（也就是新的 state）。需要注意的是 Reducer 必须是纯函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">app.model(&#123;</span><br><span class="line">  namespace: <span class="string">'todos'</span>, <span class="comment">//model 的 namespace</span></span><br><span class="line">  state: [], <span class="comment">// model 的初始化数据</span></span><br><span class="line">  reducers: &#123;</span><br><span class="line">    <span class="comment">// add 方法就是 reducer，可以看到它其实非常简单就是把老的 state 和接收到的数据处理下，返回新的 state</span></span><br><span class="line">    add(state, &#123; <span class="attr">payload</span>: todo &#125;) &#123;</span><br><span class="line">      <span class="keyword">return</span> state.concat(todo);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><strong>2.5、dva - Effect</strong><br>Effect 被称为副作用，在我们的应用中，最常见的就是异步操作，Effects 的最终流向是通过 Reducers 改变 State。</p>
<p>核心需要关注下 put, call, select。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">app.model(&#123;</span><br><span class="line">  namespace: <span class="string">'todos'</span>,</span><br><span class="line">  effects: &#123;</span><br><span class="line">    *addRemote(&#123; <span class="attr">payload</span>: todo &#125;, &#123; put, call, select &#125;) &#123;</span><br><span class="line">      <span class="keyword">const</span> todos = <span class="keyword">yield</span> select(<span class="function"><span class="params">state</span> =&gt;</span> state.todos); <span class="comment">// 这边的 state 来源于全局的 state，select 方法提供获取全局 state 的能力，也就是说，在这边如果你有需要其他 model 的数据，则完全可以通过 state.modelName 来获取</span></span><br><span class="line">      <span class="keyword">yield</span> call(addTodo, todo); <span class="comment">// 用于调用异步逻辑，支持 promise 。</span></span><br><span class="line">      <span class="keyword">yield</span> put(&#123; <span class="attr">type</span>: <span class="string">'add'</span>, <span class="attr">payload</span>: todo &#125;); <span class="comment">// 用于触发 action 。这边需要注意的是，action 所调用的 reducer 或 effects 来源于本 model 那么在 type 中不需要声明命名空间，如果需要触发其他非本 model 的方法，则需要在 type 中声明命名空间，如 yield put(&#123; type: 'namespace/fuc', payload: xxx &#125;);</span></span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>2.6、dva - Subscription</strong><br>Subscriptions 是一种从 源 获取数据的方法，它来自于 elm。</p>
<p>Subscription 语义是订阅，用于订阅一个数据源，然后根据条件 dispatch 需要的 action。数据源可以是当前的时间、服务器的 websocket 连接、keyboard 输入、geolocation 变化、history 路由变化等等。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> key <span class="keyword">from</span> <span class="string">'keymaster'</span>;</span><br><span class="line">...</span><br><span class="line">app.model(&#123;</span><br><span class="line">  namespace: <span class="string">'count'</span>,</span><br><span class="line">  subscriptions: &#123;</span><br><span class="line">    keyEvent(dispatch) &#123;</span><br><span class="line">      key(<span class="string">'⌘+up, ctrl+up'</span>, () =&gt; &#123; dispatch(&#123;<span class="attr">type</span>:<span class="string">'add'</span>&#125;) &#125;);</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>2.7、dva - Router</strong><br>这里的路由通常指的是前端路由，由于我们的应用现在通常是单页应用，所以需要前端代码来控制路由逻辑，通过浏览器提供的 History API 可以监听浏览器 url 的变化，从而控制路由相关操作。</p>
<p> dva 实例提供了 router 方法来控制路由，使用的是 react-router。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Router, Route &#125; <span class="keyword">from</span> <span class="string">'dva/router'</span>;</span><br><span class="line">	app.router(<span class="function">(<span class="params">&#123;history&#125;</span>) =&gt;</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<h4 id="3、dva-的六部曲"><a href="#3、dva-的六部曲" class="headerlink" title="3、dva 的六部曲"></a>3、dva 的六部曲</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">'./index.html'</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">'./index.css'</span>;</span><br><span class="line"><span class="keyword">import</span> dva <span class="keyword">from</span> <span class="string">'dva'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 1. Initialize</span></span><br><span class="line"><span class="keyword">const</span> app = dva();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2. Plugins - 该项为选择项</span></span><br><span class="line"><span class="comment">//app.use(&#123;&#125;);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 3. Model 的注册</span></span><br><span class="line"><span class="comment">//app.model(require('./models/example'));</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 4. 配置 Router</span></span><br><span class="line">app.router(<span class="built_in">require</span>(<span class="string">'./router'</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 5. Start</span></span><br><span class="line">app.start(<span class="string">'#root'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 6. Connect components and models</span></span><br><span class="line"><span class="keyword">const</span> App = connect(mapStateToProps)(Component);</span><br></pre></td></tr></table></figure>

<p><strong>注： 人为新增 model 后记得 model 要在 index.js 中予以注册，当然使用脚手架功能并不存在这个问题</strong></p>

    </div>
    
    <div class="post-footer">
        <div>
            
                转载声明：商业转载请联系作者获得授权,非商业转载请注明出处 © <a href="" target="_blank">Snippet</a>
            
        </div>
        <div>
            
        </div>
    </div>
</article>

<div class="article-nav prev-next-wrap clearfix">
    
        <a href="/blog/2019/07/31/React 组件之间的通信/" class="pre-post btn btn-default" title='React - 组件之间的通信'>
            <i class="fa fa-angle-left fa-fw"></i><span class="hidden-lg">上一篇</span>
            <span class="hidden-xs">React - 组件之间的通信</span>
        </a>
    
    
        <a href="/blog/2019/07/21/React状态管理器 - Mbox/" class="next-post btn btn-default" title='React状态管理器 - Mbox'>
            <span class="hidden-lg">下一篇</span>
            <span class="hidden-xs">React状态管理器 - Mbox</span><i class="fa fa-angle-right fa-fw"></i>
        </a>
    
</div>


    <div id="comments">
        
	
    <div id="vcomments" class="valine"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="/blog/assets/valine.min.js"></script>

    <script>
        new Valine({
            av: AV,
            el: '#vcomments',
            appId: 'xOKV9J4UeQAtVkvnJC7Kq2Jn-gzGzoHsz',
            appKey: 'erIpQac4azoCmgfBB7Dl9maa',
            placeholder: '说点什么吧',
            notify: false,
            verify: true,
            avatar: 'mm',
            meta: 'nick,mail'.split(','),
            pageSize: '10',
            path: window.location.pathname,
            lang: ''.toLowerCase()
        })
    </script>


    </div>





                </main>
                
                    <aside id="article-toc" role="navigation" class="col-md-4">
    <div class="widget">
        <h3 class="title">Table of Contents</h3>
        
            <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#启动一个-dva-应用"><span class="toc-text">启动一个 dva 应用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1、dva-项目-src-目录结构"><span class="toc-text">1、dva 项目 src 目录结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2、官网解释"><span class="toc-text">2、官网解释</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3、dva-的六部曲"><span class="toc-text">3、dva 的六部曲</span></a></li></ol></li></ol>
        
    </div>
</aside>

                
            </div>
        </div>
    </section>
    <footer class="main-footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</footer>

<a id="back-to-top" class="icon-btn hide">
	<i class="fa fa-chevron-up"></i>
</a>




    <div class="copyright">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="busuanzi">
    
</div>

            </div>
            <div class="col-sm-12">
                <span>Copyright &copy; 2017
                </span> |
                <span>
                    Powered by <a href="//hexo.io" class="copyright-links" target="_blank" rel="nofollow">Hexo</a>
                </span> |
                <span>
                    Theme by <a href="//github.com/shenliyang/hexo-theme-snippet.git" class="copyright-links" target="_blank" rel="nofollow">Snippet</a>
                </span>
            </div>
        </div>
    </div>
</div>







<script src="/blog/js/app.js?rev=@@hash"></script>

</body>
</html>